package cn.lysoy.demo.aspect;

import cn.lysoy.demo.domain.pojo.JobExceptionLog;
import cn.lysoy.demo.service.JobExceptionLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 定时任务切面
 */
@Slf4j
@Aspect
@Component
public class JobsAspect {
    private String className; // 类名
    private String methodName;      // 方法名
    private String startTime; // 开始时间
    private String endTime; // 结束时间
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private JobExceptionLogService jobExceptionLogService;

    @Pointcut("@annotation(org.springframework.scheduling.annotation.Scheduled)")
    public void pointCut(){}

    @Before("pointCut()")
    public void beforeHandle(JoinPoint joinPoint) {
        getTaskName(joinPoint);
        Date date = new Date();
        this.startTime = sdf.format(date);
        log.info(this.startTime+" "+this.className+"."+this.methodName+"方法开始----");
    }

    @AfterThrowing(pointcut = "pointCut()", throwing = "e")
    public void afterThrowingHandle(Exception e) {
        Date date = new Date();
        this.endTime = sdf.format(date);
        log.info(this.endTime+" "+this.className+"."+this.methodName+"方法异常----");
        JobExceptionLog jobExceptionLog = new JobExceptionLog();
        jobExceptionLog.setStartDate(this.startTime);
        jobExceptionLog.setEndDate(this.endTime);
        jobExceptionLog.setClassName(this.className);
        jobExceptionLog.setMethodName(this.methodName);
        jobExceptionLog.setStatus(0);
        jobExceptionLog.setException(e.getClass().getName());
        jobExceptionLog.setMessage(e.getMessage());
        try {
            jobExceptionLogService.save(jobExceptionLog);
        }catch (Exception ex) {
            log.error(ex.getMessage());
        }

    }

    /**
     * 获取定时任务类加名字
     */
    private void getTaskName(JoinPoint joinPoint){
        this.className = joinPoint.getTarget().getClass().getSimpleName();
        this.methodName = joinPoint.getSignature().getName();
        return;
    }

}
